<?
	/* Se asegura que el archivo es incluido por el index */
		defined( 'LOAD_MODULE_ACTION' ) or die( 'No esta permitido el acceso directo a ' . __FILE__ );
	/* Cuando se hace el include del archivo automaticamente crea un objeto y lo guarda en una variable temporal */
		$this->oTmpObject = new Generador_exe( $this );

class Generador_exe extends Exe
{
	function Generador_exe( &$oModule )
		{
			$this->oModule = &$oModule;
			$this->oDatabase = openMetadataDB ( getParam('cPathModule') );
		}
	function getTableStructure( $cPathModule, $cTabla )
	{
		$cArchivo =  $cPathModule  .  "/db" . strrchr ( $cPathModule  , "/" ) . ".xml";
		$oXML = simplexml_load_file( $cArchivo );
		$aDataType = array();
		$aTable = array();
		foreach ($oXML->SETTINGS->DATATYPES->children() as $datatype)
		{
			$aDataType[(int)$datatype->attributes()->ID]['TypeName'] = (string)$datatype->attributes()->TypeName;
			$aDataType[(int)$datatype->attributes()->ID]['IDGroup'] = (int)$datatype->attributes()->IDGroup;
		}
		foreach ($oXML->METADATA->TABLES->children() as $table)
		{
			if ( (string)$table->attributes()->Tablename == $cTabla )
			{
				// Busca las Relaciones de la tabla
				foreach ($oXML->METADATA->RELATIONS->children() as $relation)
				{
					if ( (int)$relation->attributes()->DestTable == (int)$table->attributes()->ID )
					{
						$aFields = explode( "\\n", (string)$relation->attributes()->FKFields);
						if ( count($aFields) == 2)
						{
							list( $cFieldA, $cFieldB ) = explode("=", $aFields[0]);
							$cTableSource = "";
							foreach ($oXML->METADATA->TABLES->children() as $tableSource)
							{
								if ( (int)$tableSource->attributes()->ID == (int)$relation->attributes()->SrcTable ) { $cTableSource = (string) $tableSource->attributes()->Tablename; break; }
							}
							$aRelation[$cFieldA]['TableName'] = $cTableSource;
							$aRelation[$cFieldA]['FieldName'] = $cFieldB;
						}
					}
				}

				$nColumn = 0;
				foreach( $table->COLUMNS->children() as $aColumn )
				{
					$aTable[$nColumn]['Name'] 			= (string)$aColumn->attributes()->ColName;
					$aTable[$nColumn]['TypeGroup'] 		= $aDataType[(int)$aColumn->attributes()->idDatatype]['IDGroup'];
					$aTable[$nColumn]['Type'] 			= $aDataType[(int)$aColumn->attributes()->idDatatype]['TypeName'];
					$aTable[$nColumn]['Length'] 			= trim(str_replace( ")","",str_replace( "(","",$aColumn->attributes()->DatatypeParams)));//$aColumn->attributes()->Width;
					$aTable[$nColumn]['isPrimary'] 		= (int)$aColumn->attributes()->PrimaryKey;
					$aTable[$nColumn]['isMandatory'] 		= (int)$aColumn->attributes()->NotNull;
					$aTable[$nColumn]['isAutoIncrement']	= (int)$aColumn->attributes()->AutoInc;
					$aTable[$nColumn]['isForeignKey'] 	= (int)$aColumn->attributes()->IsForeignKey;
					$aTable[$nColumn]['DefaultValue'] 	= (string)$aColumn->attributes()->DefaultValue;
					$aTable[$nColumn]['Comments'] 		= (string)$aColumn->attributes()->Comments;
					// Si tiene una FK Busca los demas datos en la matriz de relaciones
					if ( $aTable[$nColumn]['isForeignKey'] == 1)
					{
						$aTable[$nColumn]['ForeignTable'] = $aRelation[$aTable[$nColumn]['Name']]['TableName'];
						$aTable[$nColumn]['ForeignField'] = $aRelation[$aTable[$nColumn]['Name']]['FieldName'];
					}
					$nColumn++;
				}
			}
		}
		return $aTable;
	}
	function createClass()
	{
			$cPathModule = getParam('cPathModule')  ;
			$oModBase =& loadModule("base");
			$oModBase->loadLibrary("reporte");
			$oForm = $this->oModule->loadClass( 'generador_frm' );
			$aData = array();
			extract( $oForm->getFieldArray() );
			// Valida que tenga los datos minimos
			if ( !$ncClase || !$cPathModule ) return false;
			// Arma los parametros para mandarle al listado
				if ( $cNombrePlural == '' ) $cNombrePlural = $cNombre . 's';
				$aData[0][0]['Nombre2'] =  strtoupper($cNombre);
				$aData[0][0]['Tabla'] =  $cTabla;
				for( $cPrefijo= '', $nIndex=0; $nIndex < strlen($cTabla); $nIndex++)
				{
					if ( ord($cTabla[$nIndex]) >= 65 && ord($cTabla[$nIndex]) <= 90) 
					{
						$cPrefijo .= $cTabla[$nIndex];
						$cAux = $cTabla[$nIndex+1] . $cTabla[$nIndex+2];
					}
				}
				$aData[0][0]['Prefijo'] = substr($cPrefijo. $cAux, 0, 3);
				$aData[0][0]['NombreClase'] = '';
				for( $nIndex = 2; $nIndex < strlen($cTabla); $nIndex++ )
				{
					$aData[0][0]['NombreClase'] .= $nIndex > 2 && ord($cTabla[$nIndex]) >= 65 && ord($cTabla[$nIndex]) <= 90  ?  "_" . strtolower($cTabla[$nIndex]) : $cTabla[$nIndex];
				}
				$aData[0][0]['NombrePlural2'] = strtoupper($cNombrePlural);
				$aData[0][0]['Nombre'] = $cNombre;
				$aData[0][0]['NombrePlural'] = $cNombrePlural;
				$aData[0][0]['Archivo'] = strtolower($cNombre);
				$aData[0][0]['cdSubModulo'] = $cdSubModulo;
				$aData[0][0]['ncSubModulo'] = $ncSubModulo;
			// Busca la metadata de la tabla
				$aData[1] = $this->getTableStructure( $cPathModule, $cTabla );
			// Arma el listado
				$cTemplateCode= join(file(  $this->oModule->cPathRpt . "/clase_lst/" . $cRpt ));
				$cSalida =  parseTemplate($cTemplateCode, null, $aData, $this->oDatabase, $bParam );
			// Actualiza la metadata de la clase
				$cDescripcion = arraytoString( $oForm->getFieldArray() ) ;
				$this->oDatabase->update( "stClase", "cDescripcion", $cDescripcion, "WHERE", "ncClase", $ncClase );
			if ( $nModo == 1 )
			{
				echo "<textarea rows='30' cols='80' >";
				echo $cSalida ;
				echo "</textarea>";
				exit();
			} else
			{
				$cFisico = $this->oDatabase->getData( "SELECT cFisico FROM stClase WHERE ncClase = $ncClase" )  ;
				$cDirectorio = obtenerDirectorioClase ( $cPathModule , $ncClase );
				$fd= fopen( $cPathModule  . "/" . $cDirectorio  . "/" . $cFisico , "w");
				fwrite( $fd, 	$cSalida );
				fclose($fd);
				chmod($cPathModule  . "/" . $cDirectorio  . "/" . $cFisico, 0775);
			}
	}
	function createMetadata()
	{
			$oModBase =& loadModule("base");
			$oModBase->loadLibrary("reporte");
			$oForm = $this->oModule->loadClass( 'generador_frm' );
			$aData = array();
			extract( $oForm->getFieldArray() );
			if ( $ncSubModulo )
			{
				$cdSubModulo = $this->oDatabase->getData("SELECT cDirectorio from stSubModulo WHERE ncSubModulo = $ncSubModulo");
				//
				list ( $nDesde, $nHasta )= $this->oDatabase->getArray("select nDesde, nHasta FROM stSubModulo WHERE ncSubModulo = $ncSubModulo" );
				$nDesde += 1000; $nHasta += 1000;
				$ncClase = $this->oDatabase->nextKey("stClase", "ncClase", "ncClase between $nDesde and $nHasta ");
				if ( $ncClase < $nDesde ) $ncClase  = $nDesde;
			} else
			{
				$ncClase = $this->oDatabase->nextKey("stClase", "ncClase" );
				if ( $ncClase < 1000 ) $ncClase  = 1000;
				$ncSubModulo = "null";
			}
			$ncAccion = $this->oDatabase->nextKey("stAccion", "ncAccion");
			if ( $cNombrePlural == '' ) $cNombrePlural = $cNombre . 's';
			$aData[0][0]['Nombre2'] =  strtoupper($cNombre);
			$aData[0][0]['NombreClase'] = '';
			for( $nIndex = 2; $nIndex < strlen($cTabla); $nIndex++ )
			{
				$aData[0][0]['NombreClase'] .= $nIndex > 2 && ord($cTabla[$nIndex]) >= 65 && ord($cTabla[$nIndex]) <= 90  ?  "_" . strtolower($cTabla[$nIndex]) : $cTabla[$nIndex];
			}
			$aData[0][0]['NombrePlural2'] = strtoupper($cNombrePlural);
			$aData[0][0]['Nombre'] = $cNombre;
			$aData[0][0]['NombrePlural'] = $cNombrePlural;
			$aData[0][0]['Archivo'] = strtolower($aData[0][0]['NombreClase']);
			$aData[0][0]['cdSubModulo'] = $cdSubModulo;
			$aData[0][0]['ncSubModulo'] = $ncSubModulo;
			$aData[0][0]['cDescripcion'] = arraytoString( $oForm->getFieldArray() ) ;
			$aData[0][0]['ncClase1'] =  $ncClase++;
			$aData[0][0]['ncClase2'] = $ncClase++;
			$aData[0][0]['ncClase3'] = $ncClase++;
			$aData[0][0]['ncClase4'] = $ncClase++;
			$aData[0][0]['ncClase5'] = $ncClase++;
			$aData[0][0]['ncAccion1'] = $ncAccion++;
			$aData[0][0]['ncAccion2'] =  $ncAccion++;
			$aData[0][0]['ncAccion3'] =  $ncAccion++;
			$aData[0][0]['ncAccion4'] =  $ncAccion++;
			$aData[0][0]['ncAccion5'] = $ncAccion++;
			$cTemplateCode= join(file(  $this->oModule->cPathRpt . "/accion_lst/" . $cRpt ));
			$cSalida =  parseTemplate($cTemplateCode, null, $aData, $this->oDatabase, $bParam );
			if ( $nModo == 1 )
			{
				echo "<textarea rows='30' cols='80'>";
				echo $cSalida ;
				echo "</textarea>";
				exit();
			} else
			{
				//SQL
				$cSql = extractLanguage ( $cSalida, "SQL") ;
				$aInstrucciones = explode ( ";", $cSql );
				foreach( $aInstrucciones  as $cInstruccion )
				{
					$this->oDatabase->execute( $cInstruccion );
					//echo $this->oDatabase->cSql . "<br>";
				}
				// FILE
				$cFile = extractLanguage ( $cSalida, "FILE") ;
				$fd= fopen( $cPathModule  . "/tabla_var.php", "a");
				fwrite( $fd, 	$cFile );
				fclose($fd);
				chmod($cPathModule  . "/tabla_var.php", 0775);
				//echo $cFile ;
				// BATCH
				$cBatch = extractLanguage ( $cSalida, "BATCH") ;
			}

	}
}

?>
